package colm.lagou.city.controller;

import colm.lagou.city.pojo.City;
import colm.lagou.city.service.CityService;
import com.lagou.common.entity.Result;
import com.lagou.common.entity.StatusCode;
import com.sun.org.apache.regexp.internal.RE;
import jdk.nashorn.internal.ir.CallNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/city")
@CrossOrigin      //解决跨域问题
public class CityController {
    @Autowired
    private CityService cityService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询所有
     */
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll(){
        int b = 0;
        int c = 12/b;
        return new Result(true, StatusCode.OK,"查询所有成功",cityService.findAll());
    }

    /**
     * 根据id查询
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public Result findById(@PathVariable String id){
        //1.先去redis中取，取到直接返回
        City city = (City) redisTemplate.opsForValue().get("city1_" + id);
        //2.如果没有，查询数据，并且存到缓存中
        if (city==null){
            city = cityService.findById(id);
            redisTemplate.opsForValue().set("city1_"+id,city);
        }
        return new Result(true,StatusCode.OK,"根据id查询成功",city);
    }

    /**
     * 增加
     */
    @RequestMapping(method = RequestMethod.POST)
    public Result add(@RequestBody City city){
        cityService.add(city);
        return new Result(true,StatusCode.OK,"增加成功");
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    public Result update(@RequestBody City city,@PathVariable String id){
        //删除缓存
        redisTemplate.delete("city1_"+id);
        city.setId(id);
        cityService.update(city);
        //需要重复保存
        City citynew = cityService.findById(id);
        redisTemplate.opsForValue().set("city1_"+id,citynew);
        return new Result(true,StatusCode.OK,"修改成功");
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id){
        redisTemplate.delete("city1_"+id);
        cityService.delete(id);
        return new Result(true,StatusCode.OK,"删除成功");
    }

    /**
     * 查询可用城市的前三条
     */
    public Result findTop3AndStateIsTrue(){
        return new Result(true,StatusCode.OK,"查询成功",cityService.findTop3AndStateIsTrue());
    }

    /**
     * state  状态0禁用 1启用 2热门
     * 把一个城市从禁用改为启用状态
     */
    @RequestMapping(value = "/updateCityEnable/{id}",method = RequestMethod.PUT)
    public Result updateCityEnable(@PathVariable String id){
        cityService.updateCityEnable(id);
        return new Result(true,StatusCode.OK,"修改城市状态成功");
    }
}
